package com.lottery.ruok.lottrey.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.CommonFragmentPagerAdapter;
import com.lottery.ruok.lottrey.adapter.CommonFragmentStatePagerAdapter;
import com.lottery.ruok.lottrey.eventbusObject.FavorDeleted;
import com.lottery.ruok.lottrey.eventbusObject.GotoBuyPage;
import com.lottery.ruok.lottrey.eventbusObject.LogOut;
import com.lottery.ruok.lottrey.eventbusObject.LoginSuccess;
import com.lottery.ruok.lottrey.eventbusObject.RefreshRoomStatus;
import com.lottery.ruok.lottrey.eventbusObject.ReloadLotteryEvent;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetWholeCategoryRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetWholeCategoryResponse;
import com.lottery.ruok.lottrey.ui.ShapeIndicatorView;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import ui.NavigateBar;
import utils.Utils;
/*
*
* 购票大厅
* */

public class BuyLotteryMainFragment extends BaseMainFragment {
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private boolean isPrepared;
    private boolean mHasLoadedOnce;
    private CommonFragmentStatePagerAdapter adapter;
    private List<BaseFragment> fragments = new ArrayList<>();
    private List<String> titles = new ArrayList<>();
    private List<String> codes = new ArrayList<>();
    private int size;
    private View emptyLayout;
    private View mShowTipLayout;

    @BindView(R.id.navigateBar)
    NavigateBar navigateBar;
    @BindView(R.id.custom_indicator)
    ShapeIndicatorView shapeIndicatorView;
    @BindView(R.id.swipe_container)
    SwipeRefreshLayout swipeRefreshLayout;
    private FragmentManager childFragmentManager;

    private void setEmtpyView(){
        if (emptyLayout == null && getView() != null) {
            ViewStub stub = getView().findViewById(R.id.no_net_viewstub);
            View view = stub.inflate();
            emptyLayout = view.findViewById(R.id.no_net_view);
            emptyLayout.setBackgroundResource(R.color.bg_grey);
            emptyLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    getList(true);
                }
            });
        }
    }



    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        childFragmentManager = getChildFragmentManager();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ReloadLotteryEvent event) {
        getList(false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginSuccess event) {
        getList(false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent1(LogOut event) {
        getList(false);
    }


    private void initViewPager(ArrayList<GetWholeCategoryResponse> getWholeCategoryResponses){
        size = getWholeCategoryResponses.size();
        fragments.clear();
        titles.clear();
        codes.clear();
        for (int i = 0; i <size; i++) {
            if(i==size-1){
                fragments.add(AllLotteryFragment.newInstance());
            }else{
                fragments.add(CategoryFragment.newInstance(i));
            }
            titles.add(getWholeCategoryResponses.get(i).getName());
            codes.add(getWholeCategoryResponses.get(i).getCode());
        }
        if(adapter==null){
            adapter = new CommonFragmentStatePagerAdapter(childFragmentManager,fragments,titles);
            mViewPager.setAdapter(adapter);
            mTabLayout.setupWithViewPager(mViewPager);
            mTabLayout.setTabMode(TabLayout.MODE_FIXED);
            shapeIndicatorView.setupWithTabLayout(mTabLayout);
            shapeIndicatorView.setupWithViewPager(mViewPager);
            mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    fragments.get(position).setSwipState();
                    if(mShowTipLayout != null){
                        mShowTipLayout.setVisibility(View.GONE);
                        UserInfo.setShowTip(false);
                    }
                }

                @Override
                public void onPageScrollStateChanged(int state) {
                }
            });
        }else{
            adapter.notifyDataSetChanged();
        }

        if (fragments.size() > 0) {
            mViewPager.setOffscreenPageLimit(fragments.size());
        }

    }

    private void getList(final boolean isFirst){
        RetrofitBase.getRetrofit().create(GetWholeCategoryRequest.class).getResult(UserInfo.getToken(), 0, 0)
                .compose(RxHelper.<ArrayList<GetWholeCategoryResponse>>handleResult())
                .subscribe(new RxSubscribe<ArrayList<GetWholeCategoryResponse>>(getActivity()) {
                    @Override
                    protected void _onNext(ArrayList<GetWholeCategoryResponse> getWholeCategoryResponses) {

                        if(getWholeCategoryResponses.size()>0&&size!=getWholeCategoryResponses.size()){
                            initViewPager(getWholeCategoryResponses);
                        }

                        for (int i = 0; i <fragments.size(); i++) {
                            BaseFragment fragment = fragments.get(i);
                            if(i==fragments.size()-1){
                                ((AllLotteryFragment)fragment).refresh(getWholeCategoryResponses);
                            }else{
                                fragment.setDatas(getWholeCategoryResponses.get(i));
                            }

                        }
                        swipeRefreshLayout.setRefreshing(false);
                        if(emptyLayout != null && emptyLayout.getVisibility() == View.VISIBLE){
                            emptyLayout.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        swipeRefreshLayout.setRefreshing(false);
                        if(adapter == null || adapter.getCount() == 0){
                            setEmtpyView();
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return isFirst;
                    }
                });
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }

        try {
            Field field = ViewPager.class.getDeclaredField("mTouchSlop"); // 通过ViewPager类得到字段，不能通过实例得到字段。
            field.setAccessible(true); // 设置Java不检查权限。
            field.setInt(mViewPager, 5);
        } catch (Exception e2) {
            e2.printStackTrace();
        }

        getList(true);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getList(false);
                EventBus.getDefault().post(new RefreshRoomStatus());
            }
        });

        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        swipeRefreshLayout.setEnabled(false);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        swipeRefreshLayout.setEnabled(true);
                        break;
                }
                return false;
            }
        });

        mHasLoadedOnce = true;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(getUserVisibleHint()){
            if(UserInfo.getShowTip()){
                if(mShowTipLayout == null){
                    ViewStub stub = getActivity().findViewById(R.id.showTipLayout);
                    View view = stub.inflate();
                    mShowTipLayout = view.findViewById(R.id.show_layout);
                    View bottom_view = mShowTipLayout.findViewById(R.id.bottom_view);
                    bottom_view.setOnTouchListener(new View.OnTouchListener() {
                        float diffX = 0;
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            if(event.getAction() == MotionEvent.ACTION_DOWN){
                                diffX = event.getX();
                            } else if(event.getAction() == MotionEvent.ACTION_MOVE){
                                if (Math.abs(event.getX() - diffX) > Utils.dip2px(getActivity(), 20)) {
                                    mShowTipLayout.setVisibility(View.GONE);
                                    UserInfo.setShowTip(false);
                                }
                            }
                            return true;
                        }
                    });
                    View know = mShowTipLayout.findViewById(R.id.know);
                    know.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mShowTipLayout.setVisibility(View.GONE);
                            UserInfo.setShowTip(false);
                        }
                    });
                } else {
                    mShowTipLayout.setVisibility(View.VISIBLE);
                }
            }
        } else {
            if(UserInfo.getShowTip()){
                if(mShowTipLayout != null){
                    mShowTipLayout.setVisibility(View.GONE);
                }
            }
        }
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.buy_fragment, container, false);
        ButterKnife.bind(this, view);
        mViewPager = view.findViewById(R.id.vp_view);
        mTabLayout = view.findViewById(R.id.tabs);
        isPrepared = true;
        lazyLoad();

        return view;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent2(FavorDeleted favorDeleted) {
        getList(false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent2(GotoBuyPage favorDeleted) {
        if (!Utils.isEmpty(favorDeleted.getCode())) {
            int pageCode = getPageCode(favorDeleted);
            mViewPager.setCurrentItem(pageCode);
        }
    }

    private int getPageCode(GotoBuyPage favorDeleted) {
        if (codes != null) {
            for (int i = 0; i < codes.size(); i++) {
                    if (codes.get(i) != null && codes.get(i).equals(favorDeleted.getCode())) {
                        return i;
                    }
                }
            }
        return 0;
    }
}